package com.laf.manage.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laf.common.exception.ServiceException;
import com.laf.common.utils.SecurityUtils;
import com.laf.common.utils.StringUtils;
import com.laf.manage.constant.CommonConstant;
import com.laf.manage.domain.po.Category;
import com.laf.manage.mapper.mp.CategoryMapper;
import com.laf.manage.service.ICategoryService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分类管理Service业务层处理
 *
 * @author zian
 * @date 2024-10-30
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 查询分类管理列表
     *
     * @param category 分类管理
     * @return 分类管理
     */
    @Override
    public List<Category> selectCategoryList(Category category) {
        List<Category> categoryList = categoryMapper.selectList(buildQueryWrapper(category));
        return categoryList;
    }

    public boolean delById(Long id) {
        // 1. 判断分类是否存在
        Category category = getById(id);
        if (category == null) {
            throw new ServiceException("分类不存在");
        }
        // 2. 查询对应的分类下是否存在子分类，如果存在禁止删除
        List<Category> categoryList = lambdaQuery()
                .eq(Category::getParentId, category.getId())
                .list();
        if (CollectionUtils.isNotEmpty(categoryList)) {
            throw new ServiceException("该分类下存在子分类，请先删除子分类");
        }
        // 删除分类
        return removeById(id);

    }

    @Override
    public boolean addCategory(Category category) {
        setAncestors(category);
        String username = SecurityUtils.getUsername();
        // 补充基础信息
        LocalDateTime now = LocalDateTime.now();
        category.setCreateTime(now);
        category.setUpdateTime(now);
        category.setCreateBy(username);
        category.setUpdateBy(username);


        return save(category);

    }

    @Override
    public boolean editCategory(Category dto) {
        Category dbCategory = getById(dto.getId());
        if (dbCategory == null) throw new ServiceException("分类不存在");

        // 补充祖级列表
        setAncestors(dto);

        String username = SecurityUtils.getUsername();
        // 补充基础信息
        LocalDateTime now = LocalDateTime.now();
        dto.setUpdateTime(now);
        dto.setUpdateBy(username);
        // 更新分类数据
        return updateById(dto);
    }

    /**
     * 获取分类树列表
     * @return
     */
    @Override
    public List<Category> getCategoryTreeList() {
        // 1. 获取所有分类
        List<Category> list =  list();
        if (CollUtil.isEmpty(list)){
            return new ArrayList<>();
        }

        List<Category> result = new ArrayList<>();

        //2. 获取所有根节点
        List<Category> rootNode = list.stream()
                .filter(item -> item.getParentId().equals(CommonConstant.CATEGORY_ROOT_ID))
                .collect(Collectors.toList());
        for (Category category : rootNode) {
            List<Category> children = getChildren(list, category);
            category.setChildren(children);
            result.add(category);
        }

        return result;
    }

    /**
     * 递归获取子节点
     * @param list 分类列表
     * @param category 父级分类
     * @return 子分类
     */
    private List<Category> getChildren(List<Category> list, Category category){
        List<Category> children = list.stream()
                .filter(item -> item.getParentId().equals(category.getId()))
                .collect(Collectors.toList());

        for (Category child : children) {
            List<Category> categories = getChildren(list, child);
            child.setChildren(categories);
        }

        return children;
    }


    /**
     * 设置父级分类
     *
     * @param category 新增或者需要修改的分类po
     */
    private void setAncestors(Category category) {
        if (category.getParentId() != 0) {
            Category parentCategory = getById(category.getParentId());
            if (parentCategory == null) {
                throw new ServiceException("父级分类不存在");
            }
            if (parentCategory.getAncestors().split(",").length >= 2) {
                throw new ServiceException("不允许设置第三级分类");
            }
            String ancestors = parentCategory.getAncestors() + "," + category.getParentId();
            category.setAncestors(ancestors);
        } else {
            category.setAncestors("0");
        }
    }


    private LambdaQueryWrapper<Category> buildQueryWrapper(Category query) {
        LocalDateTime beginTime = query.getBeginTime();
        LocalDateTime endTime = query.getEndTime();
        LambdaQueryWrapper<Category> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(query.getCategoryName()), Category::getCategoryName, query.getCategoryName());
        lqw.between(beginTime != null && endTime != null, Category::getCreateTime, beginTime, endTime);
        lqw.orderByAsc(Category::getOrderNum);
        lqw.orderByDesc(Category::getCreateTime);
        return lqw;
    }

}
